package main

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	consulapi "github.com/hashicorp/consul/api"
	"go-grpc-lb/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func main() {
	r := gin.Default()

	r.GET("/index", func(c *gin.Context) {
		// 第一步：连接服务端
		conn, err := grpc.Dial(
			"consul://10.0.0.102:8500/grpc_test?wait=14s&tag=lqz",
			//grpc.WithInsecure(),
			grpc.WithTransportCredentials(insecure.NewCredentials()),
			grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
		)
		if err != nil {
			fmt.Println(err)
			c.JSON(200, "连接grpc服务异常")
		}
		//defer 关闭
		defer conn.Close()
		// 第二步：创建客户端调用
		client := proto.NewGreeterClient(conn)
		// 测试默认值
		resp, err := client.SayHello(context.Background(), &proto.HelloRequest{
			Name: "lqz",
			Age:  19,
		})
		if err != nil {
			fmt.Println(err)
			c.JSON(200, "服务器错误")
		}
		c.JSON(200, resp.Reply)
	})

	r.Run()
}

// 可能有多个grpc服务，我们只返回一个
func getFirstGrpcRegister() (host string, port int, err error) {
	// 创建连接consul服务配置
	config := consulapi.DefaultConfig()
	config.Address = "10.0.0.102:8500"
	client, err := consulapi.NewClient(config)
	if err != nil {
		fmt.Println("consul client error : ", err)
	}
	//res, err := client.Agent().Services()
	res, err := client.Agent().ServicesWithFilter(`Service=="grpc_test"`)
	if err != nil {
		return "", 0, err
	}
	fmt.Println(res)
	for _, value := range res {
		host = value.Address
		port = value.Port
	}
	return
}
